package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.uitl.SmsProperty;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lsyandwh:
 * @create 2022-12-07 16:43
 */
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String NUMBER_CODE = "api.sms.phone.";

    @Override
    public void sendCode(String phone) {

        ValueOperations ops = redisTemplate.opsForValue();

        //判断该手机号短信发送过于频繁
        if(null != ops.get(NUMBER_CODE + phone)){
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
        }

        DefaultProfile defaultProfile =
                DefaultProfile.getProfile(SmsProperty.REGION_ID,
                SmsProperty.KEY_ID,
                SmsProperty.KEY_SECRET);
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);

        // 配置请求参数
        CommonRequest commonRequest = new CommonRequest();
        try {
            //通用参数
            commonRequest.setSysAction("SendSms");// 产品接口
            commonRequest.setSysVersion("2017-05-25");// 版本
            commonRequest.setSysDomain("dysmsapi.aliyuncs.com");// 网关
            commonRequest.setSysMethod(MethodType.POST);
            //接口参数
            commonRequest.putQueryParameter("RegionId", "cn-shenzhen");
            commonRequest.putQueryParameter("PhoneNumbers",phone);
            commonRequest.putQueryParameter("SignName", SmsProperty.SIGN_NAME);
            commonRequest.putQueryParameter("TemplateCode", SmsProperty.TEMPLATE_CODE);
            //生成验证码
            double random = Math.random();
            String str = String.valueOf(random);
            String code = str.substring(2, 6);
            HashMap<String,Object> map = new HashMap<>();
            map.put("code",code);
            Gson gson = new Gson();
            String param = gson.toJson(map);

            commonRequest.putQueryParameter("TemplateParam",param);
            // 发送请求
            CommonResponse commonResponse = iAcsClient.getCommonResponse(commonRequest);

            boolean success = commonResponse.getHttpResponse().isSuccess();
            int status = commonResponse.getHttpResponse().getStatus();
            Map map1 = JSON.parseObject(commonResponse.getData(), Map.class);
            String ok = (String) map1.get("Code");

            if(success == true && status == 200 && ok.equals("OK")){
                //将验证码存入缓存中，并设置过期时间

                ops.set(NUMBER_CODE + phone,code,300, TimeUnit.SECONDS);
            }else {
                throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR);
            }

        } catch (ClientException e) {
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR,e);
        }
    }
}
